package com.fly.hello.service;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import com.fly.core.utils.ShellExecutor;
import com.fly.core.utils.jackson.JsonBeanUtils;
import com.fly.hello.entity.Article;
import com.fly.hello.entity.BlogData;

import lombok.extern.slf4j.Slf4j;

/**
 * DataService
 */
@Slf4j
@Service
public class DataService
{
    @Autowired
    WebClient webClient;
    
    /**
     * 获取url数据列表
     * 
     * @return
     */
    @Cacheable(cacheNames = "data", key = "'articles'", sync = true)
    public List<Article> getArticles()
    {
        // 容器运行，镜像需安装curl
        log.info("★★★★★★★★ getData from webApi ★★★★★★★★");
        // webClient.get().uri("https://00fly.online/upload/data.json").acceptCharset(StandardCharsets.UTF_8).accept(MediaType.APPLICATION_JSON).retrieve().bodyToMono(BlogData.class).block().getData().getList();
        return IntStream.rangeClosed(1, 2)
            .mapToObj(i -> String.format("curl -e \"blog.csdn.net\" \"https://blog.csdn.net/community/home-api/v1/get-business-list?page=%s&size=100&businessType=blog&username=qq_16127313\"", i))
            .map(cmd -> ShellExecutor.execute(cmd))
            .map(json -> parseToArticles(json))
            .flatMap(List::stream)
            .collect(Collectors.toList());
    }
    
    /**
     * 解析json为List
     * 
     * @param json
     * @return
     */
    private static List<Article> parseToArticles(String json)
    {
        try
        {
            return JsonBeanUtils.jsonToBean(json, BlogData.class, true).getData().getList();
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
            return Collections.emptyList();
        }
    }
}